//
//  ObjModel.m
//  oschina
//
//  Created by 如佳 陈 on 2015/06/19.
//  Copyright (c) 2015年 crj. All rights reserved.
//

#import "ObjModel.h"
//#import <objc/objc-runtime.h>
#import <objc/runtime.h>

@implementation ObjModel

- (instancetype)initWithXMLElement:(ONOXMLElement *)ele{
    if (self = [super init]) {
        [self setValuesForKeysWithXMLElement:ele];
    }
    return self;
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key{

}

- (void)setValuesForKeysWithXMLElement:(ONOXMLElement *)ele{
    for (ONOXMLElement *child in [ele children]) {
        if ([child children].count > 0) {
            if (![self respondsToSelector:NSSelectorFromString([child tag])]) {
                return;
            }
            objc_property_t property = class_getProperty([self class], [[child tag] cStringUsingEncoding:NSUTF8StringEncoding]);
            const char *attrs = property_getAttributes(property);
            NSString* propertyAttributes = [NSString stringWithUTF8String:attrs];
            if([propertyAttributes containsString:@"Array"]){
                [self setValue:[[NSMutableArray alloc]init] forKey:[child tag]];
                
//                for (ONOXMLElement *subChild in [child children]) {
//                    [[self valueForKey:[child tag]] addObject:@"a"];
//                }
            }else if([propertyAttributes containsString:@"Dictionary"]){
                [self setValue:[[NSMutableDictionary alloc]init] forKey:[child tag]];
                for (ONOXMLElement *subChild in [child children]) {
                    [[self valueForKey:[child tag]] setObject:[subChild stringValue] forKey:[subChild tag]];
                }
            }else {
                NSString *error = [NSString stringWithFormat:@"%@ must be a dictionary or array",[child tag]];
                NSAssert(NO, error);
            }
        }else {
            [self setValue:[child stringValue] forKey:[child tag]];
        }
    }
}

+ (NSArray *)listWithXMLDocumentPath:(id)path{
    NSMutableArray *result = [[NSMutableArray alloc]init];
    for (ONOXMLElement *ele in path) {
        id model = [[self alloc]initWithXMLElement:ele];
        [result addObject:model];
    }
    return result;
}

@end
